﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace LoadForecast
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("1. Import load data;");
            Console.WriteLine("2. Generate data set;");
            Console.WriteLine("3. Export training data;");
            Console.WriteLine("4. Export test data;");
            Console.WriteLine("5. Update holiday data;");
            Console.WriteLine("6. Update weekday data;");
            Console.WriteLine("7. Import temperature data;");
            Console.WriteLine("8. Update temperature data;");
            Console.WriteLine("9. Update peak load data;");
            Console.WriteLine("A. Update load difference data;");
            Console.WriteLine("B. Update last year data;");
            Console.WriteLine("C. Update last month data;");
            while (true)
            {
                switch (Console.ReadKey().Key)
                {
                    case ConsoleKey.D1:                        
                        //ImportLoadData();
                        break;
                    case ConsoleKey.D2:
                        GenerateDataSet();
                        break;
                    case ConsoleKey.D3:
                        ExportTrainingData();
                        break;
                    case ConsoleKey.D4:
                        ExportTestData();
                        break;
                    case ConsoleKey.D5:
                        UpdateHolidayAttribute();
                        break;
                    case ConsoleKey.D6:
                        UpdateWeekAttribute();
                        break;
                    case ConsoleKey.D7:
                        ImportTemperatureData();
                        break;
                    case ConsoleKey.D8:
                        UpdateTemperatureAttributeForPowerLoad();
                        break;
                    case ConsoleKey.D9:
                        UpdatePeakLoad();
                        break;
                    case ConsoleKey.A:
                        UpdateLoadDifference();
                        break;
                    case ConsoleKey.B:
                        UpdateLastYearLoad();
                        break;
                    case ConsoleKey.C:
                        UpdateLastWeekMonthLoad();
                        break;
                    default:
                        Console.WriteLine("Invalid command.");
                        break;
                }
            }
        }

        static void ImportLoadData()
        {
            Console.WriteLine("Start to import power load data.");
            List<string> holidayList = new List<string>();
            using (var context = new PowerLoadEntities())
            {
                foreach (Holiday holidayItem in context.Holidays)
                {
                    holidayList.Add(string.Format("{0}-{1}", holidayItem.Month, holidayItem.Day));
                }
            }

            HSSFWorkbook hssfworkbook;
            using (FileStream file = new FileStream("Load1999.xls", FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);

                NPOI.SS.UserModel.Sheet sheet = hssfworkbook.GetSheetAt(0);
                System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                int lastRowNum = sheet.LastRowNum;
                int firstRowNum = sheet.FirstRowNum;
                NPOI.SS.UserModel.Row firstRow = sheet.GetRow(0);
                List<string> timeArrary = new List<string>();

                for (int colIndex = 3; colIndex < firstRow.LastCellNum; colIndex++)
                {
                    timeArrary.Add(firstRow.GetCell(colIndex).ToString());
                }

                for (int rowIndex = 1; rowIndex <= lastRowNum; rowIndex++)
                {
                    NPOI.SS.UserModel.Row row = sheet.GetRow(rowIndex);
                    if (row.GetCell(0) != null)
                    {
                        int year = Convert.ToInt32(row.GetCell(0).ToString());
                        int month = Convert.ToInt32(row.GetCell(1).ToString());
                        int day = Convert.ToInt32(row.GetCell(2).ToString());

                        for (int i = 3; i < row.LastCellNum; i++)
                        {
                            NPOI.SS.UserModel.Cell cell = row.GetCell(i);

                            long load = Convert.ToInt64(cell.ToString());

                            using (var context = new PowerLoadEntities())
                            {
                                LoadData loadData = new LoadData();

                                loadData.Time = timeArrary[i - 3];
                                string[] tempTimeArr = timeArrary[i - 3].Split(new char[] { ':' });
                                //if (tempTimeArr[0].StartsWith("0"))
                                //{
                                //    tempTimeArr[0] = tempTimeArr[0];
                                //}
                                int hour = Convert.ToInt32(tempTimeArr[0]);
                                int minute = Convert.ToInt32(tempTimeArr[1]);
                                DateTime dateTime = new DateTime(year, month, day, hour, minute, 0);
                                
                                if (loadData.Time == "0:00")
                                {
                                    dateTime = dateTime.AddDays(1);
                                }

                                loadData.DateTime = dateTime;
                                loadData.Year = dateTime.Year;
                                loadData.Month = dateTime.Month;
                                loadData.Day = dateTime.Day;

                                loadData.L1 = "";
                                loadData.L2 = "";
                                loadData.TemperatureAttr = 0;
                                if (dateTime.DayOfWeek == DayOfWeek.Friday ||
                                    dateTime.DayOfWeek == DayOfWeek.Saturday)
                                {
                                    loadData.WeekdayAttr = 1;
                                }
                                else
                                {
                                    loadData.WeekdayAttr = 0;
                                }

                                if (holidayList.Contains(string.Format("{0}-{1}", dateTime.Month, dateTime.Day)))
                                {
                                    loadData.HolidayAttr = 1;
                                }
                                else
                                {
                                    loadData.HolidayAttr = 0;
                                }

                                loadData.Load = Convert.ToInt64(cell.ToString());
                                Console.WriteLine("Load Data:{0}/{1}/{2} {3} == {4}", dateTime.Year, dateTime.Month, dateTime.Day, loadData.Time, loadData.Load);
                                context.AddToLoadDatas(loadData);
                                context.SaveChanges();
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                Console.Read();
            }
        }

        static void ImportTemperatureData()
        {
            Console.WriteLine("Start to import temperature data.");
            
            HSSFWorkbook hssfworkbook;
            using (FileStream file = new FileStream("Temperature1999.xls", FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);

                NPOI.SS.UserModel.Sheet sheet = hssfworkbook.GetSheetAt(0);
                System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                int lastRowNum = sheet.LastRowNum;
                int firstRowNum = sheet.FirstRowNum;
                NPOI.SS.UserModel.Row firstRow = sheet.GetRow(0);
                List<string> timeArrary = new List<string>();

                for (int colIndex = 3; colIndex < firstRow.LastCellNum; colIndex++)
                {
                    timeArrary.Add(firstRow.GetCell(colIndex).ToString());
                }

                for (int rowIndex = 1; rowIndex <= lastRowNum; rowIndex++)
                {
                    NPOI.SS.UserModel.Row row = sheet.GetRow(rowIndex);
                    if (row.GetCell(0) != null)
                    {
                        NPOI.SS.UserModel.Cell dateTimecell = row.GetCell(0);
                        if (!string.IsNullOrEmpty(dateTimecell.ToString()))
                        {
                            DateTime dateTime = Convert.ToDateTime(dateTimecell.ToString());

                            NPOI.SS.UserModel.Cell temperatureCell = row.GetCell(1);
                            decimal temperature = Convert.ToDecimal(temperatureCell.ToString());
                            using (var context = new PowerLoadEntities())
                            {
                                DayPeakLoad temperatureData = new DayPeakLoad();
                                temperatureData.Year = dateTime.Year;
                                temperatureData.Month = dateTime.Month;
                                temperatureData.Day = dateTime.Day;
                                temperatureData.AverageTemperature = temperature;

                                Console.WriteLine("Temperature:{0}/{1}/{2} {3}", temperatureData.Year, temperatureData.Month, temperatureData.Day, temperatureData.AverageTemperature);
                                context.AddToDayPeakLoads(temperatureData);
                                context.SaveChanges();
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                Console.Read();
            }
        }

        static void GenerateDataSet()
        {          
            Console.WriteLine("Start to generate data set.");
            using (var context = new PowerLoadEntities())
            {
                List<string> holidayList = new List<string>();
                foreach (Holiday holidayItem in context.Holidays)
                {
                    holidayList.Add(string.Format("{0}-{1}-{2}", holidayItem.Year, holidayItem.Month, holidayItem.Day));
                }

                List<LoadData> loadDatas = context.LoadDatas.ToList();
                for (int index = 0; index < loadDatas.Count; index++)
                {
                    LoadData loadDataEntity = loadDatas[index];
                    // 前7天相同时刻的负荷值
                    //List<LoadData> L1Datas = loadDatas.Where(l=>l.DateTime > fiveDaysAgo && l.DateTime < loadDataEntity.DateTime && l.Time == loadDataEntity.Time).OrderBy(l=>l.DateTime).ToList();
                    //string l1Data = "";
                    //if (L1Datas.Count == 6)
                    //{
                    //    for (int l1Index = 0; l1Index < L1Datas.Count; l1Index++)
                    //    {
                    //        l1Data += string.Format("{0}:{1} ", l1Index+1, L1Datas[l1Index].Load);
                    //    }
                    //    loadDataEntity.L1 = l1Data;
                    //}
                    //Console.WriteLine(string.Format("Generate for {0} L1:{1}", loadDataEntity.DateTime, loadDataEntity.L1));

                    //string l1str = string.Format("1:{0} 2:{1} ", loadDataEntity.HolidayAttr, loadDataEntity.TemperatureAttr);
                    string l1str = "";//string.Format("1:{0} ", loadDataEntity.HolidayAttr);
                
                    DateTime halfHourAgo = loadDataEntity.DateTime.AddMinutes(-30);
                    DateTime oneHourAgo = loadDataEntity.DateTime.AddHours(-1);
                    DateTime oneAndHalfHourAgo = loadDataEntity.DateTime.AddHours(-1).AddMinutes(-30);
                    DateTime twoHourAgo = loadDataEntity.DateTime.AddHours(-2);
                    DateTime twoAndHalfHourAgo = twoHourAgo.AddMinutes(-30);
                    LoadData halfHourAgoLoad = loadDatas.Where(l => l.DateTime == halfHourAgo).FirstOrDefault();
                    LoadData oneHourAgoLoad = loadDatas.Where(l=>l.DateTime == oneHourAgo).FirstOrDefault();
                    LoadData oneAndHalfHourAgoLoad = loadDatas.Where(l => l.DateTime == oneAndHalfHourAgo).FirstOrDefault();
                    LoadData twoHourAgoLoad = loadDatas.Where(l => l.DateTime == twoHourAgo).FirstOrDefault();
                    LoadData twoAndHalfHourAgoLoad = loadDatas.Where(l => l.DateTime == twoAndHalfHourAgo).FirstOrDefault();
                                                           
                    if (halfHourAgoLoad != null)
                    {
                        l1str += string.Format("{0}:{1} ", 1, halfHourAgoLoad.Load); 
                    }
                    if (oneHourAgoLoad != null)
                    {
                        l1str += string.Format("{0}:{1} ", 2, oneHourAgoLoad.Load); 
                    }
                    if (oneAndHalfHourAgoLoad != null)
                    {
                        l1str += string.Format("{0}:{1} ", 3, oneAndHalfHourAgoLoad.Load);
                    }
                    if (twoHourAgoLoad != null)
                    {
                        l1str += string.Format("{0}:{1} ", 4, twoHourAgoLoad.Load);
                    }
                    if (twoAndHalfHourAgoLoad != null)
                    {
                        l1str += string.Format("{0}:{1} ", 5, twoAndHalfHourAgoLoad.Load);
                    }

                    List<LoadData> loadsWithSameAttribute = loadDatas.Where(l => l.HolidayAttr == loadDataEntity.HolidayAttr &&
                        l.DateTime <= loadDataEntity.DateTime &&
                        l.Day != loadDataEntity.Day &&
                        l.Time == loadDataEntity.Time)
                        .OrderByDescending(l => l.DateTime).ToList();
                    string l7str = l1str;
                    if (loadsWithSameAttribute.Count >= 5)
                    {
                        List<LoadData> loadListWithSameAttribute = loadsWithSameAttribute.Take(5).ToList();
                        l1str += string.Format("{0}:{1} ", 6, loadListWithSameAttribute[0].Load);
                        l1str += string.Format("{0}:{1} ", 7, loadListWithSameAttribute[1].Load);
                        l1str += string.Format("{0}:{1} ", 8, loadListWithSameAttribute[2].Load);
                        l1str += string.Format("{0}:{1} ", 9, loadListWithSameAttribute[3].Load);
                        l1str += string.Format("{0}:{1} ", 10, loadListWithSameAttribute[4].Load);
                    }

                    l1str += string.Format("{0}:{1} ", 11, loadDataEntity.AverageTemperature);
                    loadDataEntity.L4 = l1str;
                    //l1str += string.Format("{0}:{1} ", 11, loadDataEntity.TemperatureAttr);
                    //loadDataEntity.L3 = l1str;

                    //List<LoadData> loadsWith = loadDatas.Where(l => //l.HolidayAttr == loadDataEntity.HolidayAttr &&
                    //    l.DateTime <= loadDataEntity.DateTime &&
                    //    l.Day != loadDataEntity.Day &&
                    //    l.Time == loadDataEntity.Time)
                    //    .OrderByDescending(l => l.DateTime).ToList();

                    //if (loadsWith.Count >= 7)
                    //{
                    //    List<LoadData> loadListWithSameAttribute = loadsWith.Take(7).ToList();
                    //    l7str += string.Format("{0}:{1} ", 6, loadsWith[0].Load);
                    //    l7str += string.Format("{0}:{1} ", 7, loadsWith[1].Load);
                    //    l7str += string.Format("{0}:{1} ", 8, loadsWith[2].Load);
                    //    l7str += string.Format("{0}:{1} ", 9, loadsWith[3].Load);
                    //    l7str += string.Format("{0}:{1} ", 10, loadsWith[4].Load);
                    //    l7str += string.Format("{0}:{1} ", 11, loadsWith[5].Load);
                    //    l7str += string.Format("{0}:{1} ", 12, loadsWith[6].Load);
                    //}
                    
                    //loadDataEntity.L10 = l7str;
                    //string tiemStr = string.Format("{0}-{1}-{2}", loadDataEntity.Year, loadDataEntity.Month, loadDataEntity.Day);
                    //if (holidayList.Contains(tiemStr))
                    //{
                    //    l7str += string.Format("{0}:{1} ", 13, 1);
                    //}
                    //else                    
                    //{
                    //    l7str += string.Format("{0}:{1} ", 13, 0);
                    //}
                    //loadDataEntity.L11 = l7str;
                    //l7str += string.Format("{0}:{1} ", 14, loadDataEntity.WeekdayAttr);
                    //loadDataEntity.L12 = l7str;
                    //string l13str = l7str;
                    //l7str += string.Format("{0}:{1} ", 15, loadDataEntity.AverageTemperature);
                    //loadDataEntity.L13 = l7str;
                    //l13str += string.Format("{0}:{1} ", 15, loadDataEntity.TemperatureAttr);
                    //loadDataEntity.L14 = l13str;


                    //// 前6个时刻的负荷值
                    //DateTime twoHoursAgo = loadDataEntity.DateTime.AddHours(-2);
                    //List<LoadData> L2Datas = loadDatas.Where(l => l.DateTime >= twoHoursAgo && l.DateTime < loadDataEntity.DateTime).OrderBy(l => l.DateTime).ToList();
                    //string l2Data = "";
                    //if (L2Datas.Count == 4)
                    //{
                    //    for (int l2Index = 0; l2Index < L2Datas.Count; l2Index++)
                    //    {
                    //        l2Data += string.Format("{0}:{1} ", l2Index+7, L2Datas[l2Index].Load);
                    //    }
                    //    loadDataEntity.L2 = l2Data;
                    //}



                    //DateTime oneHoursAgo = loadDataEntity.DateTime.AddHours(-1);
                    //LoadData L2Datas = loadDatas.Where(l => l.DateTime >= oneHoursAgo && l.DateTime < loadDataEntity.DateTime).OrderByDescending(l => l.DateTime).ToList().FirstOrDefault();

                    //string l2str = string.Format("1:{0} 2:{1} 3:{2} 4:{3} 5:{4} 6:{5}", (int)loadDataEntity.DateTime.DayOfWeek, loadDataEntity.DateTime.Month,
                    //    loadDataEntity.HolidayAttr, loadDataEntity.DateTime.DayOfYear, loadDataEntity.AverageTemperature, loadDataEntity.DateTime.Hour * 2 + (loadDataEntity.DateTime.Minute == 0 ? 0 : 1)
                    //    );
                    //if (L2Datas != null)
                    //{
                    //    l2str += " 7:" + L2Datas.Load;
                    //}
                    //if (loadDataEntity.LoadDifference != null)
                    //{
                    //    l2str += " 8:" + loadDataEntity.LoadDifference;
                    //}
                    //if (loadDataEntity.LoadLastYear != null)
                    //{
                    //    l2str += " 9:" + loadDataEntity.LoadLastYear;
                    //}
                    //loadDataEntity.L2 = l2str;

                    //DateTime oneYear = loadDataEntity.DateTime.AddYears(-1);

                    //loadDataEntity.L3 = string.Format("1:{0} 2:{1} 3:{2} 4:{3} 5:{4} 6:{5}", (int)loadDataEntity.DateTime.DayOfWeek, loadDataEntity.DateTime.Month, loadDataEntity.HolidayAttr, loadDataEntity.DateTime.DayOfYear, loadDataEntity.AverageTemperature, loadDataEntity.DateTime.Hour*2+(loadDataEntity.DateTime.Minute==0?0:1));

                    //// 去年同期前后两个时刻的负荷值
                    //DateTime lastYear = loadDataEntity.DateTime.AddYears(-1);
                    //DateTime lastYearOneHourAgo = lastYear.AddHours(-1);
                    //DateTime lastYearOneHourAfter = lastYear.AddHours(1);
                    //List<LoadData> L3Datas = loadDatas.Where(l=>l.DateTime >= lastYearOneHourAgo && l.DateTime <= lastYearOneHourAfter).OrderBy(l=>l.DateTime).ToList();
                    //string l3Data = "";
                    //if (L3Datas.Count == 5)
                    //{
                    //    for (int l3Index = 0; l3Index < L3Datas.Count; l3Index++)
                    //    {
                    //        l3Data += string.Format("{0}:{1} ", l3Index + 10, L3Datas[l3Index].Load);
                    //    }
                    //    loadDataEntity.L3 = l3Data;
                    //}
                    //else
                    //{
                    //    for (int l3Index = 0; l3Index < 5; l3Index++)
                    //    {
                    //        l3Data += string.Format("{0}:{1} ", l3Index + 10, loadDataEntity.Load);
                    //    }
                    //    loadDataEntity.L3 = l3Data;
                    //}
                    Console.WriteLine(string.Format("Generate for {0} L4:{1}", loadDataEntity.DateTime, loadDataEntity.L4));
                    context.SaveChanges();                    
                }
            }
        }

        static void ExportTrainingData()
        {
            Console.WriteLine("Start to export training data.");

            StringBuilder sb = new StringBuilder();

            using (var context = new PowerLoadEntities())
            {
                //int dataCount = context.LoadDatas.Where(l => l.L1.Length > 0 &&
                //l.L2.Length > 0).Count();
                //160450
                //DateTime startDate = new DateTime(1997, 1, 20);
                //DateTime endDate = new DateTime(1999, 1, 1);
                DateTime startDate = new DateTime(1997, 11, 1);
                DateTime endDate = new DateTime(1998, 3, 1);
                List<LoadData> loadDatas = context.LoadDatas.Where(l => 
                l.DateTime >= startDate && l.DateTime < endDate).OrderBy(l => l.DateTime).ToList();

                foreach (LoadData loadDataEntity in loadDatas)
                {
                    sb.AppendLine(string.Format("{0} {1}", loadDataEntity.Load, 
                        loadDataEntity.L13));

                    Console.WriteLine(string.Format("{0} {1}", loadDataEntity.Load,
                        loadDataEntity.L13));
                }                
            }

            using (StreamWriter outfile = new StreamWriter(@"\powerload.txt"))
            {
                outfile.Write(sb.ToString());
            }

            Console.WriteLine("Finish to export training data.");
        }

        static void ExportTestData()
        {
            Console.WriteLine("Start to export test data.");

            StringBuilder sb = new StringBuilder();

            using (var context = new PowerLoadEntities())
            {
                //int dataCount = context.LoadDatas.Where(l => l.L1.Length > 0 &&
                //l.L2.Length > 0).Count();
                //160450

                //DateTime startDate = new DateTime(1999, 1, 1);
                //DateTime endDate = new DateTime(1999, 1, 2);
                DateTime startDate = new DateTime(1998, 11, 1);
                DateTime endDate = new DateTime(1998, 12, 31);

                List<LoadData> loadDatas = context.LoadDatas.Where(l =>                
                l.DateTime >= startDate && l.DateTime <= endDate).OrderBy(l => l.DateTime).ToList();

                foreach (LoadData loadDataEntity in loadDatas)
                {
                    sb.AppendLine(string.Format("{0} {1}", loadDataEntity.Load,
    loadDataEntity.L13));

                    Console.WriteLine(string.Format("{0} {1}", loadDataEntity.Load,
                        loadDataEntity.L13));
                }
            }

            using (StreamWriter outfile = new StreamWriter(@"\powertest.txt"))
            {
                outfile.Write(sb.ToString());
            }

            Console.WriteLine("Finish to export test data.");
        }

        static void UpdateHolidayAttribute()
        {
            List<string> holidayList = new List<string>();
            using (var context = new PowerLoadEntities())
            {
                foreach (Holiday holidayItem in context.Holidays)
                {
                    holidayList.Add(string.Format("{0}-{1}-{2}", holidayItem.Year, holidayItem.Month, holidayItem.Day));
                }
            }

            using (var context = new PowerLoadEntities())
            {
                List<LoadData> loadDatas = context.LoadDatas.ToList();
                for (int index = 0; index < loadDatas.Count; index++)
                {
                    LoadData loadDataEntity = loadDatas[index];
                    string tiemStr = string.Format("{0}-{1}-{2}", loadDataEntity.Year, loadDataEntity.Month, loadDataEntity.Day);
                    if (holidayList.Contains(tiemStr))
                    {
                        loadDataEntity.HolidayAttr = 1;
                        context.SaveChanges(); 
                    }
                    Console.WriteLine(string.Format("Update holiday attribute for {0} L3:{1}", loadDataEntity.DateTime, loadDataEntity.HolidayAttr));
                }
            }
        }

        static void UpdateWeekAttribute()
        {
            using (var context = new PowerLoadEntities())
            {
                List<LoadData> loadDatas = context.LoadDatas.ToList();
                for (int index = 0; index < loadDatas.Count; index++)
                {
                    LoadData loadDataEntity = loadDatas[index];
                    switch (loadDataEntity.DateTime.DayOfWeek)
                    {
                        case DayOfWeek.Monday:
                            loadDataEntity.WeekdayAttr = 1;
                            break;
                        case DayOfWeek.Tuesday:
                            loadDataEntity.WeekdayAttr = 2;
                            break;
                        case DayOfWeek.Wednesday:
                            loadDataEntity.WeekdayAttr = 3;
                            break;
                        case DayOfWeek.Thursday:
                            loadDataEntity.WeekdayAttr = 4;
                            break;
                        case DayOfWeek.Friday:
                            loadDataEntity.WeekdayAttr = 5;
                            break;
                        case DayOfWeek.Saturday:
                            loadDataEntity.WeekdayAttr = 6;
                            break;
                        case DayOfWeek.Sunday:
                            loadDataEntity.WeekdayAttr = 7;
                            break;
                    }
                    context.SaveChanges(); 
                    Console.WriteLine(string.Format("Update holiday attribute for {0} Weekday:{1}", loadDataEntity.DateTime, loadDataEntity.WeekdayAttr));
                }
            }
        }

        static void UpdateTemperatureAttributeForPowerLoad()
        {
            using (var context = new PowerLoadEntities())
            {
                List<LoadData> loadDatas = context.LoadDatas.ToList();
                for (int index = 0; index < loadDatas.Count; index++)
                {
                    LoadData loadDataEntity = loadDatas[index];
                    DayPeakLoad temperatureEntity = context.DayPeakLoads.Where(p => p.Year == loadDataEntity.Year &&
                        p.Month == loadDataEntity.Month &&
                        p.Day == loadDataEntity.Day).FirstOrDefault();
                    loadDataEntity.AverageTemperature = temperatureEntity.AverageTemperature;
                    context.SaveChanges();
                    Console.WriteLine(string.Format("Update temperature attribute for {0} tmperature:{1}", loadDataEntity.DateTime, loadDataEntity.AverageTemperature));
                }
            }
        }

        static void UpdatePeakLoad()
        {
            using (var context = new PowerLoadEntities())
            {
                List<LoadData> loadDatas = context.LoadDatas.ToList();
                for (int index = 0; index < loadDatas.Count; index++)
                {
                    LoadData loadDataEntity = loadDatas[index];

                    DayPeakLoad peakLoadEntity = context.DayPeakLoads.Where(p=>p.Year == loadDataEntity.Year &&
                        p.Month == loadDataEntity.Month && p.Day == loadDataEntity.Day).FirstOrDefault();
                    if (peakLoadEntity != null && peakLoadEntity.PeakLoad < loadDataEntity.Load)
                    {
                        peakLoadEntity.PeakLoad = (int)loadDataEntity.Load;
                        context.SaveChanges();
                        Console.WriteLine(string.Format("Update peak load for {0} PeakLoad:{1}", loadDataEntity.DateTime, loadDataEntity.Load));
                    }                    
                }
            }
        }

        static void UpdateLoadDifference()
        {
            using (var context = new PowerLoadEntities())
            {
                List<LoadData> loadDatas = context.LoadDatas.ToList();
                for (int index = 0; index < loadDatas.Count; index++)
                {
                    LoadData loadDataEntity = loadDatas[index];

                    DateTime lastYear = loadDataEntity.DateTime.AddYears(-1);
                    LoadData lastYearLoadDataEntity = loadDatas.Where(l => l.DateTime == lastYear).FirstOrDefault();
                    if (lastYearLoadDataEntity != null)
                    {
                        DateTime halfHourAgoLastYear = lastYearLoadDataEntity.DateTime.AddHours(-1);
                        LoadData lastYearHalfHourAgoLoadDataEnity = loadDatas.Where(l => l.DateTime > halfHourAgoLastYear &&
                            l.DateTime < lastYearLoadDataEntity.DateTime).FirstOrDefault();
                        if (lastYearHalfHourAgoLoadDataEnity != null)
                        {
                            loadDataEntity.LoadDifference = (int)(lastYearLoadDataEntity.Load - lastYearHalfHourAgoLoadDataEnity.Load);
                            context.SaveChanges();
                        }
                    }
                    Console.WriteLine(string.Format("Update load difference for {0} load difference:{1}", loadDataEntity.DateTime, loadDataEntity.LoadDifference));
                }
            }
        }

        static void UpdateLastYearLoad()
        {
            using (var context = new PowerLoadEntities())
            {
                List<LoadData> loadDatas = context.LoadDatas.Where(l=>l.Year > 1997).ToList();
                for (int index = 0; index < loadDatas.Count; index++)
                {
                    LoadData loadDataEntity = loadDatas[index];
                    List<LoadData> allloadDatas = context.LoadDatas.ToList();
                    DateTime lastYear = loadDataEntity.DateTime.AddYears(-1);
                    LoadData lastYearLoadDataEntity = allloadDatas.Where(l => l.DateTime == lastYear).FirstOrDefault();
                    if (lastYearLoadDataEntity != null)
                    {
                        loadDataEntity.LoadLastYear = lastYearLoadDataEntity.Load;
                        context.SaveChanges();
                    }
                    Console.WriteLine(string.Format("Update load difference for {0} load difference:{1}", loadDataEntity.DateTime, loadDataEntity.LoadLastYear));
                }
                Console.WriteLine("Finish");
            }
        }

        static void UpdateLastWeekMonthLoad()
        {
            using (var context = new PowerLoadEntities())
            {
                List<LoadData> loadDatas = context.LoadDatas.ToList();
                List<DayPeakLoad> dayPeakLoads = context.DayPeakLoads.ToList();
                List<string> holidayList = new List<string>();                
                foreach (Holiday holidayItem in context.Holidays)
                {
                    holidayList.Add(string.Format("{0}-{1}-{2}", holidayItem.Year, holidayItem.Month, holidayItem.Day));
                }

                for (int index = 0; index < loadDatas.Count; index++)
                {
                    LoadData loadDataEntity = loadDatas[index];
                    DayPeakLoad dayPeakLoadEntity = dayPeakLoads.Where(d=>d.Year == loadDataEntity.Year && d.Month == loadDataEntity.Month && d.Day == loadDataEntity.Day).FirstOrDefault();

                    // 上月
                    DateTime lastMonth = loadDataEntity.DateTime.AddMonths(-1);
                    LoadData lastMonthLoadDataEntity = loadDatas.Where(l => l.DateTime == lastMonth).FirstOrDefault();
                    if (lastMonthLoadDataEntity != null)
                    {
                        loadDataEntity.LoadLastMonth = lastMonthLoadDataEntity.Load;

                        DayPeakLoad lastMonthPeakLoadEntity = dayPeakLoads.Where(d => d.Year == lastMonthLoadDataEntity.Year && d.Month == lastMonthLoadDataEntity.Month &&
                            d.Day == lastMonthLoadDataEntity.Day).FirstOrDefault();
                        if (lastMonthPeakLoadEntity != null)
                        {
                            loadDataEntity.LoadDifferenceLastMonth = dayPeakLoadEntity.PeakLoad - lastMonthPeakLoadEntity.PeakLoad;
                        }                      
                    }

                    // 上周
                    DateTime lastWeek = loadDataEntity.DateTime.AddDays(-7);
                    LoadData lastWeekLoadDataEntity = loadDatas.Where(l => l.DateTime == lastWeek).FirstOrDefault();
                    if (lastWeekLoadDataEntity != null)
                    {
                        loadDataEntity.LoadLastWeek = lastWeekLoadDataEntity.Load;
                        DayPeakLoad lastWeekPeakLoadEntity = dayPeakLoads.Where(d => d.Year == lastWeekLoadDataEntity.Year && d.Month == lastWeekLoadDataEntity.Month &&
                            d.Day == lastWeekLoadDataEntity.Day).FirstOrDefault();
                        if (lastWeekPeakLoadEntity != null)
                        {
                            loadDataEntity.LoadDifferenceLastWeek = dayPeakLoadEntity.PeakLoad - lastWeekPeakLoadEntity.PeakLoad;
                        }
                    }

                    string todayStr = string.Format(string.Format("{0}-{1}-{2}", loadDataEntity.Year, loadDataEntity.Month, loadDataEntity.Day));
                    DateTime nextDay = loadDataEntity.DateTime.AddDays(1);
                    DateTime beforeDay = loadDataEntity.DateTime.AddDays(-1);
                    string nextdayStr = string.Format(string.Format("{0}-{1}-{2}", nextDay.Year, nextDay.Month, nextDay.Day));
                    string beforedayStr = string.Format(string.Format("{0}-{1}-{2}", beforeDay.Year, beforeDay.Month, beforeDay.Day));
                    if (holidayList.Contains(todayStr))
                    {
                        loadDataEntity.HolidayAttr = 4;
                    }
                    else if (holidayList.Contains(nextdayStr) || holidayList.Contains(beforedayStr))
                    {
                        loadDataEntity.HolidayAttr = 3;
                    }
                    else if (loadDataEntity.DateTime.DayOfWeek == DayOfWeek.Sunday || loadDataEntity.DateTime.DayOfWeek == DayOfWeek.Saturday)
                    {
                        loadDataEntity.HolidayAttr = 2;
                    }
                    else if (loadDataEntity.DateTime.DayOfWeek == DayOfWeek.Monday || loadDataEntity.DateTime.DayOfWeek == DayOfWeek.Friday)
                    {
                        loadDataEntity.HolidayAttr = 1;
                    }
                    else
                    {
                        loadDataEntity.HolidayAttr = 0;
                    }

                    if (dayPeakLoadEntity.AverageTemperature >= 0 && dayPeakLoadEntity.AverageTemperature < 10)
                    {
                        loadDataEntity.TemperatureAttr = 0;
                    }
                    else if (dayPeakLoadEntity.AverageTemperature >= 10 && dayPeakLoadEntity.AverageTemperature < 20)
                    {
                        loadDataEntity.TemperatureAttr = 1;
                    }
                    else if (dayPeakLoadEntity.AverageTemperature >= 20)
                    {
                        loadDataEntity.TemperatureAttr = 2;
                    }
                    else if (dayPeakLoadEntity.AverageTemperature >= -5 && dayPeakLoadEntity.AverageTemperature <0)
                    {
                        loadDataEntity.TemperatureAttr = 3;
                    }
                    else if (dayPeakLoadEntity.AverageTemperature >= -10 && dayPeakLoadEntity.AverageTemperature < -5)
                    {
                        loadDataEntity.TemperatureAttr = 4;
                    }
                    else
                    {
                        loadDataEntity.TemperatureAttr = 5;
                    }
                    context.SaveChanges();

                    Console.WriteLine(string.Format("Update load difference for {0} load difference:{1}", loadDataEntity.DateTime, loadDataEntity.LoadLastYear));
                }
                Console.WriteLine("Finish");
            }
        }

        static void UpdateDayPeakAttribute()
        {
            using (var context = new PowerLoadEntities())
            {
                List<DayPeakLoad> dayPeakLoads = context.DayPeakLoads.ToList();
                List<string> holidayList = new List<string>();
                foreach (Holiday holidayItem in context.Holidays)
                {
                    holidayList.Add(string.Format("{0}-{1}-{2}", holidayItem.Year, holidayItem.Month, holidayItem.Day));
                }

                for (int index = 0; index < dayPeakLoads.Count; index++)
                {
                    DayPeakLoad dayPeakLoadEntity = dayPeakLoads[index];
                    DateTime todayDate = new DateTime(dayPeakLoadEntity.Year, dayPeakLoadEntity.Month, dayPeakLoadEntity.Day);
                    dayPeakLoadEntity.DateTime = todayDate;
                    string todayStr = string.Format(string.Format("{0}-{1}-{2}", dayPeakLoadEntity.Year, dayPeakLoadEntity.Month, dayPeakLoadEntity.Day));
                    DateTime nextDay = todayDate.AddDays(1);
                    DateTime beforeDay = todayDate.AddDays(-1);
                    string nextdayStr = string.Format(string.Format("{0}-{1}-{2}", nextDay.Year, nextDay.Month, nextDay.Day));
                    string beforedayStr = string.Format(string.Format("{0}-{1}-{2}", beforeDay.Year, beforeDay.Month, beforeDay.Day));
                    if (holidayList.Contains(todayStr))
                    {
                        dayPeakLoadEntity.DayAttribute = 4;
                    }
                    else if (holidayList.Contains(nextdayStr) || holidayList.Contains(beforedayStr))
                    {
                        dayPeakLoadEntity.DayAttribute = 3;
                    }
                    else if (todayDate.DayOfWeek == DayOfWeek.Sunday || todayDate.DayOfWeek == DayOfWeek.Saturday)
                    {
                        dayPeakLoadEntity.DayAttribute = 2;
                    }
                    else if (todayDate.DayOfWeek == DayOfWeek.Monday || todayDate.DayOfWeek == DayOfWeek.Friday)
                    {
                        dayPeakLoadEntity.DayAttribute = 1;
                    }
                    else
                    {
                        dayPeakLoadEntity.DayAttribute = 0;
                    }

                    if (dayPeakLoadEntity.AverageTemperature >= 0 && dayPeakLoadEntity.AverageTemperature < 10)
                    {
                        dayPeakLoadEntity.TemperatureAttribute = 0;
                    }
                    else if (dayPeakLoadEntity.AverageTemperature >= 10 && dayPeakLoadEntity.AverageTemperature < 20)
                    {
                        dayPeakLoadEntity.TemperatureAttribute = 1;
                    }
                    else if (dayPeakLoadEntity.AverageTemperature >= 20)
                    {
                        dayPeakLoadEntity.TemperatureAttribute = 2;
                    }
                    else if (dayPeakLoadEntity.AverageTemperature >= -5 && dayPeakLoadEntity.AverageTemperature < 0)
                    {
                        dayPeakLoadEntity.TemperatureAttribute = 3;
                    }
                    else if (dayPeakLoadEntity.AverageTemperature >= -10 && dayPeakLoadEntity.AverageTemperature < -5)
                    {
                        dayPeakLoadEntity.TemperatureAttribute = 4;
                    }
                    else
                    {
                        dayPeakLoadEntity.TemperatureAttribute = 5;
                    }

                    string lstr = string.Format("1:{0} 2:{1} ", dayPeakLoadEntity.DayAttribute, dayPeakLoadEntity.TemperatureAttribute);


                    DateTime twoDaysAgo = todayDate.AddDays(-3);
                    DateTime lastMonth = todayDate.AddMonths(-1);
                    int index3 = 3;
                    List<DayPeakLoad> days = dayPeakLoads.Where(d => d.DateTime.Value > twoDaysAgo && d.DateTime.Value < todayDate).ToList();
                    DayPeakLoad lastMonthPeakLoadEntity = dayPeakLoads.Where(d => d.DateTime.Value > lastMonth && d.DateTime.Value < lastMonth).FirstOrDefault();
                    for (int index1 = 0; index1 < days.Count; index1++)
                    {
                        lstr += string.Format("{0}:{1} ", ++index3, days[index1].PeakLoad);

                        if (lastMonthPeakLoadEntity != null)
                        {

                        }
                    }
                    DateTime lastWeek = todayDate.AddDays(-7);
                    DayPeakLoad lastWeekPeakLoadEntity = dayPeakLoads.Where(d => d.DateTime.Value == lastWeek).FirstOrDefault();
                    if (lastWeekPeakLoadEntity != null)
                    {
                        lstr += string.Format("{0}:{1}", ++index3, lastWeekPeakLoadEntity.PeakLoad);

                    }

                    context.SaveChanges();

                    Console.WriteLine(string.Format("Update load difference for {0} load difference:{1}", dayPeakLoadEntity.DateTime, dayPeakLoadEntity.LStr));
                }
            }
        }
    }
}
